package com.example.demo.security;

import org.apache.tomcat.util.http.fileupload.IOUtils;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.*;


public class RSAUtil {

    public static final String CHARSET = "UTF-8";
    public static final String RSA_ALGORITHM = "RSA";

    public static Map<String,String> generateKeys(int keySize){
        try {
            KeyPairGenerator keyPairGenerator= KeyPairGenerator.getInstance(RSA_ALGORITHM);
            keyPairGenerator.initialize(keySize);
            KeyPair keyPair= keyPairGenerator.generateKeyPair();
            Key publicKey= keyPair.getPublic();
            Key privateKey= keyPair.getPrivate();
            Map<String, String> keyPairMap = new HashMap<>();
            keyPairMap.put("publicKey",encodeBase64(publicKey.getEncoded()));
            keyPairMap.put("privateKey",encodeBase64(privateKey.getEncoded()));
            return keyPairMap;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        throw new RuntimeException("generate rsa keys error.");
    }

    /**
     * 公钥加密
     * @param data
     * @param publicKeyStr
     * @return
     */
    public static String publicEncrypt(String data, String publicKeyStr){
        try{
            RSAPublicKey publicKey= getPublicKey(publicKeyStr);
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            return encodeBase64(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), publicKey.getModulus().bitLength()));
        }catch(Exception e){
            throw new RuntimeException("加密字符串:" + data + "异常", e);
        }
    }

    /**
     * 私钥解密
     * @param data
     * @param privateKeyStr
     * @return
     */
    public static String privateDecrypt(String data, String privateKeyStr){
        try{
            RSAPrivateKey privateKey= getPrivateKey(privateKeyStr);
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.getDecoder().decode(data), privateKey.getModulus().bitLength()), CHARSET);
        }catch(Exception e){
            throw new RuntimeException("解密字符串:" + data + "异常", e);
        }
    }


    /**
     * 私钥加密
     * @param data
     * @param privateKeyStr
     * @return
     */
    public static String privateEncrypt(String data, String privateKeyStr){
        try{
            RSAPrivateKey privateKey= getPrivateKey(privateKeyStr);
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            return encodeBase64(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), privateKey.getModulus().bitLength()));
        }catch(Exception e){
            throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
        }
    }


    /**
     * 公钥解密
     * @param data
     * @param publicKeyStr
     * @return
     */
    public static String publicDecrypt(String data, String publicKeyStr){
        try{
            RSAPublicKey publicKey= getPublicKey(publicKeyStr);
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.getDecoder().decode(data), publicKey.getModulus().bitLength()), CHARSET);
        }catch(Exception e){
            throw new RuntimeException("解密字符串:" + data + "异常", e);
        }
    }

    private static RSAPublicKey getPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKey));
        RSAPublicKey key = (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
        return key;
    }

    private static RSAPrivateKey getPrivateKey(String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey));
        RSAPrivateKey key = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);
        return key;
    }

    private static byte[] rsaSplitCodec(Cipher cipher, int opmode, byte[] datas, int keySize){
        int maxBlock = 0;
        if(opmode == Cipher.DECRYPT_MODE){
            maxBlock = keySize / 8;
        }else{
            maxBlock = keySize / 8 - 11;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] buff;
        int i = 0;
        try{
            while(datas.length > offSet){
                if(datas.length-offSet > maxBlock){
                    buff = cipher.doFinal(datas, offSet, maxBlock);
                }else{
                    buff = cipher.doFinal(datas, offSet, datas.length-offSet);
                }
                out.write(buff, 0, buff.length);
                i++;
                offSet = i * maxBlock;
            }
        }catch(Exception e){
            throw new RuntimeException("加解密阀值为["+maxBlock+"]的数据时发生异常", e);
        }
        byte[] resultDatas = out.toByteArray();
        IOUtils.closeQuietly(out);
        return resultDatas;
    }




    private static String encodeBase64(byte[] bytes){
        return new String(Base64.getEncoder().encode(bytes));
    }

    private static String decodeBase64(byte[] bytes){
        return new String(Base64.getDecoder().decode(bytes));
    }

    public static void main(String[] args) {
        Map<String, String> keyMap = RSAUtil.generateKeys(1024);
        String  publicKey = keyMap.get("publicKey");
        String  privateKey = keyMap.get("privateKey");
        System.out.println("公钥: " + publicKey);
        System.out.println("私钥：" + privateKey);
        String content= "莫言自己在《红高粱家族》开篇便写道：“我终于悟到：高密东北乡无疑是世界上最美丽最丑陋，最超脱最世俗，最圣洁最龌龊，" +
                "最英雄好汉最王八蛋，最能喝酒最能爱的地方。”与那些一味赞扬自己家乡的人来说，莫言的这段话或许才是对自己家乡最真实的看法，" +
                "而且这里的“丑陋，世俗，龌龊，王八蛋”等词汇并不是刻意贬低或丑化自己的家乡，而是真实地正直客观地写出其真实状况。" +
                "毫无疑问，但凡看过这部小说的人都会发现里面充满了暴力、血腥和情色的东西，但莫言在描写这些东西的时候并不是带着鄙视批评的态度去描写的，" +
                "甚至在有的部分，我们会发现莫言在情感上是认同的。在轿夫们合力杀死打劫人，余占鳌杀死单家父子，余占鳌与戴凤莲在高粱地野合，" +
                "甚至于余占鳌带领队伍与胶高大队的八路军和冷支队三种不同势力之间的斗争等，莫言都是从第三者视角去叙述的，" +
                "他并没有对其中的故事过程进行批判是对是错，只是尽力写出这个故事的种种，仿佛是亲身经历过的样子，写尽其中的美与丑。\n";
        System.out.println("明文：\r\n"+content);
        String encode= RSAUtil.privateEncrypt(content, privateKey);
        System.out.println("私钥加密：\r\n"+encode);
        String decode= RSAUtil.publicDecrypt(encode,publicKey);
        System.out.println("公钥解密：\r\n"+decode);
        System.out.println("-----------------------------------------------------------------");
        encode= RSAUtil.publicEncrypt(content,publicKey);
        System.out.println("公钥加密：\r\n"+encode);
        decode= RSAUtil.privateDecrypt(encode,privateKey);
        System.out.println("私钥解密：\r\n"+decode);

    }
}
